package br.com.educa.excessao;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import flexjson.JSONSerializer;

@Aspect
public class GerenciadorDeExcecoes {
		
	@SuppressWarnings("unchecked")
	@Around("execution(public ResponseEntity<String> br.com.educa..*(..))")
    public ResponseEntity<String> trataErro(ProceedingJoinPoint pjp) throws Throwable {
		
		try{
			return (ResponseEntity<String>) pjp.proceed();
		}catch(ConstraintViolationException e){
			e.printStackTrace();
			StringBuilder sb = new StringBuilder();
			sb.append("Erros de validação no formulário: \n");
			for(ConstraintViolation c : e.getConstraintViolations()){
				sb.append(c.getMessage()+"\n");
			}
			String erro = sb.toString();
			Exception erroEx = new Exception(erro);
			
			HttpHeaders headers = new HttpHeaders();
			headers.add("Content-Type", "application/json; charset=utf-8");
	        String json = new JSONSerializer().exclude("*.class").serialize(erroEx);
	        return new ResponseEntity<String>(json, headers, HttpStatus.INTERNAL_SERVER_ERROR);
		}catch(Exception e){
			e.printStackTrace();
			HttpHeaders headers = new HttpHeaders();
			headers.add("Content-Type", "application/json; charset=utf-8");
	        String json = new JSONSerializer().exclude("*.class").serialize(e);
	        return new ResponseEntity<String>(json, headers, HttpStatus.INTERNAL_SERVER_ERROR);
			//throw e;
		}
    }
}